import requests
import random
# import json
# from datetime import datetime

BASE_URL = "http://localhost:8080"


def print_menu():
    print("\n供应链管理系统")
    print("1. 供应商")
    print("2. 生产商")
    print("3. 经销商")
    print("0. 退出")
    print("请选择角色: ")


def get_materials_epc_id():
    # 生成一个包含前缀和随机数字的EPC ID
    prefix = "MAT"
    random_number = str(random.randint(100000, 999999))
    return f"{prefix}{random_number}"


def supplier_menu():
    while True:
        print("\n供应商操作菜单")
        print("1. 原材料入库")
        print("2. 查询原材料信息")
        print("0. 返回主菜单")
        choice = input("请选择操作: ")

        if choice == "1":
            material_name = input("请输入原材料名称: ")
            try:
                epc_id = get_materials_epc_id()
                response = requests.post(
                    f"{BASE_URL}/supplier/materials",
                    json={"epc_id": epc_id, "name": material_name},
                )
                if response.status_code == 200:
                    print("原材料入库成功！")
                    print("EPC ID:", response.json()["epc_id"])
                else:
                    print("操作失败:", response.json()["error"])
            except Exception as e:
                print("请求失败:", str(e))

        elif choice == "2":
            epc_id = input("请输入EPC ID: ")
            try:
                response = requests.get(f"{BASE_URL}/supplier/materials/{epc_id}")
                if response.status_code == 200:
                    material = response.json()
                    print("\n原材料信息:")
                    print(f"EPC ID: {material['epc_id']}")
                    print(f"名称: {material['name']}")
                    print(f"状态: {material['status']}")
                    print(f"入库时间: {material['check_in_time']}")
                    if material["status"] != "in_stock":
                        print(f"出库时间: {material['check_out_time']}")
                    print(f"转移记录: {material['trans']}")
                else:
                    print("查询失败:", response.json()["error"])
            except Exception as e:
                print("请求失败:", str(e))

        elif choice == "0":
            break


def manufacturer_menu():
    while True:
        print("\n生产商操作菜单")
        print("1. 请求原材料并生产产品")
        print("2. 查询产品信息")
        print("0. 返回主菜单")
        choice = input("请选择操作: ")

        if choice == "1":
            product_name = input("请输入产品名称: ")
            try:
                response = requests.post(
                    f"{BASE_URL}/manufacturer/products",
                    json={"product_name": product_name},
                )
                if response.status_code == 200:
                    print("产品生产成功！")
                    print("产品 EPC ID:", response.json()["epc_id"])
                else:
                    print("操作失败:", response.json()["error"])
            except Exception as e:
                print("请求失败:", str(e))

        elif choice == "2":
            epc_id = input("请输入产品 EPC ID: ")
            try:
                response = requests.get(f"{BASE_URL}/manufacturer/products/{epc_id}")
                if response.status_code == 200:
                    product = response.json()
                    print("\n产品信息:")
                    print(f"EPC ID: {product['epc_id']}")
                    print(f"名称: {product['name']}")
                    print(f"状态: {product['status']}")
                    print(f"生产时间: {product['create_time']}")
                    print(f"原材料 EPC: {product['material_epcs']}")
                    print(f"转移记录: {product['trans']}")
                else:
                    print("查询失败:", response.json()["error"])
            except Exception as e:
                print("请求失败:", str(e))

        elif choice == "0":
            break


def dealer_menu():
    while True:
        print("\n经销商操作菜单")
        print("1. 请求产品")
        print("2. 查询产品溯源信息")
        print("0. 返回主菜单")
        choice = input("请选择操作: ")

        if choice == "1":
            product_name = input("请输入产品名称: ")
            try:
                response = requests.post(
                    f"{BASE_URL}/dealer/products", json={"product_name": product_name}
                )
                if response.status_code == 200:
                    print("产品请求成功！")
                    print("产品 EPC ID:", response.json()["epc_id"])
                else:
                    print("操作失败:", response.json()["error"])
            except Exception as e:
                print("请求失败:", str(e))

        elif choice == "2":
            epc_id = input("请输入产品 EPC ID: ")
            try:
                response = requests.get(f"{BASE_URL}/dealer/products/{epc_id}/trace")
                if response.status_code == 200:
                    trace = response.json()
                    print("\n产品溯源信息:")
                    print("\n产品信息:")
                    print(f"EPC ID: {trace['product']['epc_id']}")
                    print(f"名称: {trace['product']['name']}")
                    print(f"状态: {trace['product']['status']}")
                    print(f"生产时间: {trace['product']['create_time']}")
                    print(f"转移记录: {trace['product']['trans']}")
                    print("\n原材料信息:")
                    for material in trace["materials"]:
                        print(f"\n原材料 {material['name']}:")
                        print(f"  EPC ID: {material['epc_id']}")
                        print(f"  状态: {material['status']}")
                        print(f"  入库时间: {material['check_in_time']}")
                        if material["status"] != "in_stock":
                            print(f"  出库时间: {material['check_out_time']}")
                        print(f"  转移记录: {material['trans']}")
                else:
                    print("查询失败:", response.json()["error"])
            except Exception as e:
                print("请求失败:", str(e))

        elif choice == "0":
            break


def main():
    while True:
        print_menu()
        choice = input()

        if choice == "1":
            supplier_menu()
        elif choice == "2":
            manufacturer_menu()
        elif choice == "3":
            dealer_menu()
        elif choice == "0":
            print("感谢使用！再见！")
            break
        else:
            print("无效选择，请重试")


if __name__ == "__main__":
    main()
